package com.example.tnot.Teacher.MinePart.InternalFragment.AboutStu;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import androidx.activity.OnBackPressedCallback;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import com.example.tnot.R;
import com.example.tnot.Teacher.BaseFragment.BaseBackFragment;
import com.example.tnot.Teacher.MinePart.InternalFragment.AboutStu.adapter.StudentAdapter;
import com.example.tnot.Teacher.MinePart.InternalFragment.AboutStu.itembean.Student;
import com.example.tnot.Util.popupwindow.FloatWindowService;
import com.example.tnot.Util.ToastUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class aboutstuFragment extends BaseBackFragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String mParam1;
    private String mParam2;
    View view;
    String[] items = {"数科2301班", "自动化2301班", "运动训练2301班", "体育教育2301班", "运动康复2301班"};
    private RecyclerView rv_aboutstu;
    private StudentAdapter adapter;
    private ImageView back;
    private Spinner basicSpinner;
    private OnBackPressedCallback onBackPressedCallback;
    private List<Student> students = new ArrayList<>();
    private List<Student> DefaultStudents;
    private String selectedItem;
    private Map<String, List<Student>> classStudentMap = new HashMap<>();
    // 广播接收器
    private BroadcastReceiver floatWindowReceiver;

    public aboutstuFragment() {
    }
    public static aboutstuFragment newInstance(Student student, String param2) {
        aboutstuFragment fragment = new aboutstuFragment();
        Bundle args = new Bundle();
        args.putSerializable("student", (Serializable) student);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        // 初始化广播接收器
        floatWindowReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
//                android.util.Log.d("aboutstuFragment", "接收到广播: " + intent.getAction());
                if ("com.example.tnot.FLOAT_WINDOW_CLICKED".equals(intent.getAction())) {
//                    android.util.Log.d("aboutstuFragment", "处理悬浮窗点击事件");
                    // 确保在主线程中执行导航操作
                    if (getActivity() != null && getView() != null) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    NavController navController = Navigation.findNavController(getView());
                                    navController.navigate(R.id.action_aboutstuFragment_to_stuAddFragment);
//                                    android.util.Log.d("aboutstuFragment", "导航成功");
                                } catch (Exception e) {
//                                    android.util.Log.e("aboutstuFragment", "导航失败", e);
                                }
                            }
                        });
                    }
                }
            }
        };

        // 检查并请求悬浮窗权限
        checkAndRequestOverlayPermission();
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.mine_aboutstu_fragment, container, false);
        rv_aboutstu = view.findViewById(R.id.rv_aboutStu);
        rv_aboutstu.setLayoutManager(new LinearLayoutManager(getActivity()));
        back = view.findViewById(R.id.back);
        basicSpinner = view.findViewById(R.id.sp_downlist);
        initClassStudentData(); // 初始化数据
        //初始化下拉菜单
        ArrayAdapter<String> Spinner_adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, items);
        Spinner_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        basicSpinner.setAdapter(Spinner_adapter);
        DefaultStudents = classStudentMap.getOrDefault("数科2301班", new ArrayList<>());
        adapter = new StudentAdapter(DefaultStudents);
        rv_aboutstu.setAdapter(adapter);
        //下拉菜单点击监听
        basicSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // 处理选中的项
                selectedItem = parent.getItemAtPosition(position).toString();
                List<Student> students = classStudentMap.getOrDefault(selectedItem, new ArrayList<>());
//                //根据用户选择更新学生列表
                SwitchRecycleView(selectedItem);
            }
            //初始化RecyclerView默认展示数科2301班级的数据
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                adapter = new StudentAdapter(DefaultStudents);
                rv_aboutstu.setAdapter(adapter);

            }
        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handleBackPressed();
            }
        });
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        // 注册广播接收器
        if (floatWindowReceiver != null && getActivity() != null) {
            IntentFilter filter = new IntentFilter("com.example.tnot.FLOAT_WINDOW_CLICKED");
            LocalBroadcastManager.getInstance(getActivity()).registerReceiver(floatWindowReceiver, filter);
            android.util.Log.d("aboutstuFragment", "广播接收器已注册");
        }

        // Fragment恢复时启动悬浮窗服务
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || Settings.canDrawOverlays(getActivity())) {
            startFloatWindowService();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        // 注销广播接收器
        try {
            if (floatWindowReceiver != null && getActivity() != null) {
                LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(floatWindowReceiver);
                android.util.Log.d("aboutstuFragment", "广播接收器已注销");
            }
        } catch (IllegalArgumentException e) {
            android.util.Log.w("aboutstuFragment", "广播接收器未注册或已注销");
        }

        // Fragment暂停时停止悬浮窗服务
        stopFloatWindowService();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // Fragment销毁时确保停止服务
        stopFloatWindowService();
    }
    private void startFloatWindowService() {
        Intent intent = new Intent(getActivity(), FloatWindowService.class);
        getActivity().startService(intent);
    }

    private void stopFloatWindowService() {
        Intent intent = new Intent(getActivity(), FloatWindowService.class);
        getActivity().stopService(intent);
    }

    //      静态设置数据
    private void initClassStudentData() {
        //清空数据
        classStudentMap.clear();

        // 数科2301班学生
        List<Student> shukeStudents = new ArrayList<>();
        shukeStudents.add(new Student("张俞", "2023001", "19923409819", "数科2301班"));
        shukeStudents.add(new Student("李明", "2023002", "19923409820", "数科2301班"));
        classStudentMap.put("数科2301班", shukeStudents);

        // 自动化2301班学生
        List<Student> automationStudents = new ArrayList<>();
        automationStudents.add(new Student("王强", "2023101", "19923409821", "自动化2301班"));
        automationStudents.add(new Student("赵磊", "2023102", "19923409822", "自动化2301班"));
        classStudentMap.put("自动化2301班", automationStudents);

        // 运动训练2301班学生
        List<Student> sportsTrainingStudents = new ArrayList<>();
        sportsTrainingStudents.add(new Student("刘翔", "2023201", "19923409823", "运动训练2301"));
        classStudentMap.put("运动训练2301班", sportsTrainingStudents);

        // 体育教育2301班学生
        List<Student> peStudents = new ArrayList<>();
        peStudents.add(new Student("姚明", "2023301", "19923409824", "体育教育2301"));
        classStudentMap.put("体育教育2301班", peStudents);

        // 运动康复2301班学生
        List<Student> rehabStudents = new ArrayList<>();
        rehabStudents.add(new Student("华佗", "2023401", "19923409825", "运动康复"));
        classStudentMap.put("运动康复2301班", rehabStudents);
    }
    private void SwitchRecycleView(String className) {
        List<Student> UserSelectStudents = classStudentMap.getOrDefault(className,new ArrayList<>());
        adapter = new StudentAdapter(UserSelectStudents);
        rv_aboutstu.setAdapter(adapter);
    }

    private void checkAndRequestOverlayPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(getActivity())) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                        Uri.parse("package:" + getActivity().getPackageName()));
                startActivityForResult(intent, 1);
            } else {
                // 已有权限，启动悬浮窗服务
                startFloatWindowService();
            }
        } else {
            // Android 6.0以下版本直接启动服务
            startFloatWindowService();
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (Settings.canDrawOverlays(getActivity())) {
                    // 权限已授予，启动悬浮窗服务
                    startFloatWindowService();
                } else {
                    // 权限被拒绝，可提示用户
                    ToastUtil.showCustomToast(getActivity(), "未获得悬浮窗权限，无法显示悬浮窗", Toast.LENGTH_SHORT);
                }
            }
        }
    }
}